// tableModels.js
// 定义系统支持的模型表
class ModelsLocalTable {
    constructor(app, db) {
        this.app = app;
        this.db = db;
    }

    init() {
        const sqlModelsTable = `
        CREATE TABLE IF NOT EXISTS models_local (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            model_id INTEGER NOT NULL,
            model_name TEXT NOT NULL,
            model_eng_name TEXT NOT NULL,
            model_type TEXT NOT NULL,
            model_subtype TEXT NOT NULL,
            dataset_id TEXT NOT NULL,
            dataset_name TEXT NOT NULL,
            remote_id INTEGER NOT NULL,
            env_name TEXT NOT NULL,
            train_cfg TEXT NOT NULL,
            create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );`;

        this.db.run(sqlModelsTable, (err) => {
            if (err) {
                console.error('Create "models_local" Table Failed, Error: ', err);
            }
        });
    }

    // 插入models_local记录
    // 参数定义modelInfos
    // model_id: 模型id（即models_cloud表中的id，标识一个模型）
    // dataset_id: 数据集id（即datasets表中的id，标识一个数据集）
    // remote_id: 模型运行机器的名称
    // env_name：本地/远程的环境名称
    // train_cfg: 训练配置的信息（json格式字符串）
    // ......
    async insert(modelInfo) {
        // console.log('modelInfos = ', modelInfos);
        return new Promise((resolve, reject) => {
            const { model_id, model_name, model_eng_name, model_type, model_subtype, dataset_id, dataset_name, remote_id, env_name, train_cfg } = modelInfo;
            const sqlInsert = `
                INSERT INTO models_local (model_id, model_name, model_eng_name, model_type, model_subtype, dataset_id, dataset_name, remote_id, env_name, train_cfg, create_time, update_time )
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime(CURRENT_TIMESTAMP, '+8 hour') , datetime(CURRENT_TIMESTAMP, '+8 hour'));`;
            this.db.run(sqlInsert, [model_id, model_name, model_eng_name, model_type, model_subtype, dataset_id, dataset_name, remote_id, env_name, train_cfg], function (err) {
                if (err) {
                    reject(err);
                } else {
                    resolve(this.lastID);
                }
            });
        });
    }

    // 更新数据集记录
    async update(modelInfo) {
        // console.log(`update modelInfo = `, modelInfo);
        return new Promise(async (resolve, reject) => {
            let sqlUpdateSQL = 'UPDATE models_local SET';
            const params = [];

            // update remote_id if remote_id property exitsted
            if (modelInfo.remote_id !== null && modelInfo.remote_id !== undefined) {
                sqlUpdateSQL += ' remote_id = ?,';
                params.push(modelInfo.remote_id);
            }

            // update env_name if env_name property exitsted
            if (modelInfo.env_name !== null && modelInfo.env_name !== undefined) {
                sqlUpdateSQL += ' env_name = ?,';
                params.push(modelInfo.env_name);
            }

            // Remove the trailing comma and add the WHERE clause
            sqlUpdateSQL += " update_time = datetime(CURRENT_TIMESTAMP, '+8 hour') WHERE id = ?;";
            params.push(modelInfo.id);

            // Execute the UPDATE SQL statement
            this.db.run(sqlUpdateSQL, params, (err) => {
                if (err) {
                    console.error('Error updating models_local:', err.message);
                    reject({ code: -1, msg: err.message });
                }

                // console.log(`ModelLocal with ID ${modelInfo.id} updated successfully.`);
                resolve({ code: 0, msg: 'Updated OK' });
            });
        });
    }

    // 返回models_local列表
    async GetLocalModels(id) {
        return new Promise((resolve, reject) => {
            const sqlQuery = `SELECT * FROM models_local${id ? ' WHERE id = ?' : ''};`;
            const params = id ? [id] : [];

            this.db.all(sqlQuery, params, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    }

    // 删除某个本地模型
    async delete(local_model_id) {
        const deleteStatement = `
            DELETE FROM models_local WHERE id = ?;
        `;

        return new Promise((resolve, reject) => {
            this.db.run(deleteStatement, local_model_id, (err) => {
                if (err) {
                    reject(err.message);
                } else {
                    resolve(true);
                }
            });
        });
    }
}
module.exports = { ModelsLocalTable };
